using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace  Source.Web.FrameWork
{
    public class MessageHelper
    {
        private readonly BasePage page;
        private readonly TextRepositoryManager textRepositoryManager;

        public MessageHelper(BasePage page, TextRepositoryManager textRepositoryManager)
        {
            this.page = page;
            this.textRepositoryManager = textRepositoryManager;
        }

        public void DisplayMessages(IEnumerable<string> messages, IEnumerable<IEnumerable<string>> parameters)
        {
            var entireMessage = new StringBuilder();

            for (int i = 0; i < messages.Count(); i++)
            {
                string singleMessage = messages.ElementAt(i);
                var value = GetMessageFromTextRepository(singleMessage);

                if (parameters == null)
                {
                    entireMessage.Append(value);
                }
                else
                {
                    IEnumerable<string> messageParameters = parameters.ElementAt(i);
                    entireMessage.Append(string.Format(value, messageParameters.ToArray()));
                }
                entireMessage.Append("<br />\n");
            }

            SetMessageText(entireMessage.ToString());
        }

        private string GetMessageFromTextRepository(string message)
        {
            return textRepositoryManager.TryGetValue(message);
        }

        public void DisplayMessageBox(string message)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "displayInformationMessageBox", "alert('" +
                GetMessageFromTextRepository(message).Replace("'", "\\'") + "');", true);
            page.DataBind();
        }

        private void SetMessageText(string text)
        {
            page.SetMessageText(text);
        }
    }
}